<template>
	<div>
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-tree
				ref="TreeRef"
				style="max-width: 600px"
				node-key="id"
				:props="{ label: 'name' }"
				:data="state.tableData.data"
				@check-change="handleSelection"
				:default-checked-keys="choiceIds"
				show-checkbox
			/>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeDialog" size="default">取 消</el-button>
					<el-button type="primary" @click="choiceAreas" size="default">确认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { DataAreaApi } from '/@/api/shop/data/area/index';
import _ from 'lodash';

const emit = defineEmits(['choice']);
// 	:tree-props="{ children: 'children', hasChildren: 'hasChildren', checkStrictly: 'true' }"
const choiceIds = ref<any[]>([]);

const TreeRef = ref();
const props = reactive({
	label: name,
});
const treeProps = reactive({
	checkStrictly: true,
});
const state = reactive({
	choiceAreas: [] as ChoiceAreaData[],
	dialog: {
		isShowDialog: false,
		title: '选择区域',
	},
	tableData: {
		data: [],
		loading: true,
	},
});

const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

const openDialog = (hasChoiceIds: any[]) => {
	console.log('choiceId: ', hasChoiceIds);
	if (!_.isEmpty(hasChoiceIds)) {
		choiceIds.value = hasChoiceIds;
	}
	state.dialog.isShowDialog = true;
	loadData();
};

const handleSelection = (area: any, checked: boolean, indeterminate: boolean) => {
	if (checked) {
		state.choiceAreas.push({
			id: area.id,
			name: area.name,
		});
	} else {
		let newAreas = _.remove(state.choiceAreas, (obj) => {
			return obj.id == area.id && obj.name == area.name;
		});
	}
};

const choiceAlone = (obj: any) => {
	console.log('goods: ', JSON.stringify(obj));
	const choiceGoodsItem: ChoiceGoodsItem = {
		id: obj.id,
		picUrl: obj.picUrl,
		showPicUrl: obj.showPicUrl,
		goodsName: obj.goodsName,
		keywords: obj.keywords,
		vipPrice: obj.vipPrice,
	};

	const choiceAreaData: ChoiceAreaData = {
		id: obj.id,
		name: obj.name,
	};

	const choiceAreaDates = [];
	choiceAreaDates.push(choiceAreaData);
	closeDialog();
	emit('choice', choiceAreaDates);
};

const choiceAreas = () => {
	emit('choice', state.choiceAreas);
	closeDialog();
};

const loadData = async () => {
	try {
		const { data } = await DataAreaApi().tree();
		state.tableData.data = data;
		console.log('data: ', data);
	} catch (e) {
		console.log('e: ', e);
	} finally {
		state.tableData.loading = false;
	}
};

defineExpose({
	openDialog,
});
</script>

<style scoped></style>
